﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace MassIntellect.WorkIt.Frames
{
    public class Converter
    {
        public class Stream2Xml : Converter<Stream, XElement>
        {
            /// <summary>
            /// Закрытие потока после конвертирования
            /// </summary>
            [Serialize]
            public bool IsClosingStream { get; set; }

            protected override XElement convert(Stream inArg)
            {
                var res = XElement.Load(new StreamReader(inArg));
                if (IsClosingStream)
                    inArg.Close();
                return res;
            }
        }

        public class Xml2Stream : Converter<XElement, Stream>
        {
            protected override Stream convert(XElement inArg)
            {
                var ms = new MemoryStream();
                var sw = new StreamWriter(ms);
                inArg.Save(sw);
                ms.Position = 0;
                return ms;
            }
        }
    }

    public abstract class Converter<Tin, Tout> : WorkFrame
    {
        [Serialize]
        public string ContentKey { get; set; }

        [Serialize(IgnoreDefault = true)]
        public string SubjectKey { get; set; }

        private string GetContentKey()
        {
            return ContentKey.IsEmpty() ? "Content" : ContentKey;
        }

        private bool GetContent(PulseArgs args, out Tin res)
        {
            res = default(Tin);
            string key = GetContentKey();
            if (args.ContainsKey(key))
                res = (Tin)args[key];
            else
                return false;
            return true;
        }

        protected abstract Tout convert(Tin inArg);

        protected override void protectedPulse(PulseArgs args)
        {
            Tin res;
            PulseArgs a2 = args;
            if (GetContent(args, out res))
            {
                a2 = args.Clone();
                a2[GetContentKey()] = convert(res);

            }
            base.protectedPulse(a2);
        }
    }
}
